package org.zjx.command.login;

import org.zjx.command.CompositeCommand;
import org.zjx.command.CompositeCommandBuilder;
import org.zjx.command.basic.MoveCommand;
import org.zjx.command.composite.FindImageCommand;
import org.zjx.core.IWindow;
import org.zjx.state.StateManager;

import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.image.BufferedImage;

public class LoginAccountCommand extends CompositeCommand {
    public LoginAccountCommand(IWindow window, StateManager stateManager) {
        super(window, stateManager);
    }

    @Override
    protected void initializeSubCommands() {
        CompositeCommandBuilder builder = new CompositeCommandBuilder(targetWindow, stateManager);

        CompositeCommand serverFlow = builder
                .find(LoginCommandConfig.Images.ACCOUNT_ERROR_SURE_IMAGE, LoginCommandConfig.Buttons.ACCOUNT_ERROR_SURE_BUTTON, "errorSureButtonPoint")
                .find(LoginCommandConfig.Images.ACCOUNT_BACK_IMAGE, LoginCommandConfig.Buttons.ACCOUNT_BACK_BUTTON, "backButtonPoint")
                .find(LoginCommandConfig.Images.ACCOUNT_LOGIN_IMAGE, LoginCommandConfig.Buttons.ACCOUNT_LOGIN_BUTTON, "loginButtonPoint")
                .ifFound("errorSureButtonPoint", (b, context) -> {
                            // 使用熟悉的构建器语法添加系列指令
                            Point point = (Point) context.get("errorSureButtonPoint");
                            b.move(point.x, point.y)
                                    .delay(30)
                                    .click()
                                    .delay(1000);
                            Point point2 = (Point) context.get("backButtonPoint");
                            b.move(point2.x, point2.y)
                                    .delay(30)
                                    .click()
                                    .delay(1000);

                        }, (b, point) -> {
                            b.write(stateManager.getAccountState().getAccountName())
                                    .delay(200)
                                    .key(KeyEvent.VK_TAB)
                                    .delay(200)
                                    .write(stateManager.getAccountState().getPassword())
                                    .delay(200)
                                    .key(KeyEvent.VK_ENTER)
                                    .delay(1000);
                        }
                )
                .build();

        add(new MoveCommand(targetWindow, 30, 30, stateManager));
        add(serverFlow);
    }

    public static boolean validate(IWindow window, BufferedImage screenshot) {
        FindImageCommand findImageCommand = new FindImageCommand(window, screenshot, LoginCommandConfig.Images.ACCOUNT_LOGIN_IMAGE, LoginCommandConfig.Buttons.ACCOUNT_LOGIN_BUTTON);
        findImageCommand.execute();
        return findImageCommand.findImage();
    }
}